<template>
    <div class="tags-input-container">
        <label>标签</label>
        <div class="tags-input" v-on:click="focusTagInput">
            <div class="selected-tag" v-for="(selectedTag,key) in tagsArray">
                {{selectedTag}}
                <span class="remove-tag" v-on:click="removeTag(key)">X</span>
            </div>
            <input type="text" class="new-tag-input" placeholder="添加标签"
                   v-bind:id="unique"
                   v-model="currentTag"
                   v-on:keyup="searchTag"
                   v-on:keyup.enter="addNewTag"
                   v-on:keydown.down="changeIndex('down')"
                   v-on:keydown.up="changeIndex('up')"
                   v-on:keydown.delete="handleDelete"
                   v-bind:class="{'duplicate-warning':duplicateFlag}"/>
        </div>
        <div class="tag-autocomplete" v-show="showAutoComplete">
            <div class="tag-search-result" v-for="(tag, key) in tagSearchResults"
                 v-bind:class="{ 'selected-search-index' : searchSelectedIndex === key }"
                 v-on:click="selectTag( tag )">{{ tag }}
            </div>
        </div>
    </div>
</template>

<script>
    import { ROAST_CONFIG } from "../../../config";
    import { EventBus } from "../../../event-bus";
    import _ from 'lodash';

    export default {
        name: "TagInput",
        props:[
            'unique'
        ],
        data(){
          return {
              currentTag:'',
              tagsArray:[],
              duplicateFlag:false,
              tagSearchResults:[],
              searchSelectedIndex:-1,
              pauseSearch: false
          }
        },
        mounted(){
            //清空标签
            EventBus.$on('clear-tags',function (unique) {
                this.currentTag='';
                this.duplicateFlag=false;
                this.tagsArray = [];
                this.tagSearchResults=[];
                this.searchSelectedIndex=-1;
                this.pauseSearch =false;
            }.bind(this))
        },
        computed:{
            showAutoComplete(){
                return this.tagSearchResults.length!==0;
            }
        },
        methods:{
            //获取光标
            focusTagInput(){
                document.getElementById(this.unique).focus();
            },
            //删除选中标签
            removeTag(key){
                this.tagsArray.splice(key,1);
                EventBus.$emit('tags-edited',{
                    unique:this.unique,
                    tags:this.tagsArray
                })
            },
            //搜索标签
            searchTag:_.debounce(function (e) {
                if(this.currentTag.length>=2&&!this.pauseSearch){
                    axios.get(ROAST_CONFIG.API_URL+"/tags",{
                        params:{
                            keyword:this.currentTag
                        }
                    }).then(function (response) {
                        console.log(response.data);
                        this.tagSearchResults = response.data.data;
                    }.bind(this)).catch(function (error) {
                        console.log(error)
                    })
                }
            },300),
            //添加标签
            addNewTag(){
                if(this.checkDuplicates(this.currentTag)){
                    this.duplicateFlag = true;
                }else {
                    this.tagsArray.push(this.cleanTagName(this.currentTag));
                    EventBus.$emit('tags-edited',{
                        unique:this.unique,
                        tags:this.tagsArray,
                    });
                    this.resetInput();
                }
            },
            //从下拉框中选择标签
            changeIndex(direction){
                this.pauseSearch = true;
                var preIndex = this.searchSelectedIndex-1;
                var nextIndex = this.searchSelectedIndex+1;
                if(direction==='up'&&(preIndex>-1)){
                    this.searchSelectedIndex = preIndex;
                    this.currentTag = this.tagSearchResults[this.searchSelectedIndex].name;
                }
                if(direction==='down'&&(nextIndex<=(this.tagSearchResults.length-1))){
                    this.searchSelectedIndex = nextIndex;
                    this.currentTag = this.tagSearchResults[this.searchSelectedIndex].name;
                }

            },
            //删除标签
            handleDelete(){
                this.duplicateFlag =false;
                this.pauseSearch = false;
                this.searchSelectedIndex = -1;
                if(this.currentTag.length === 0){
                    this.tagsArray.splice(this.tagsArray.length-1,1);
                    EventBus.$emit('tags-edited',{unique:this.unique,tags:this.tagsArray})
                }
            },
            //选中标签
            selectTag(tag){
              if(this.checkDuplicates(tag)){
                  this.duplicateFlag = true;
              }else {
                  this.tagsArray.push(this.cleanTagName(tag));
                  EventBus.$emit('tags-edited',{
                      unique:this.unique,
                      tags:this.tagsArray,
                  });
                  this.resetInput();
              }
            },
            //检查tag是否已存在
            checkDuplicates(tag){
                tag = this.cleanTagName(tag);
                return this.tagsArray.indexOf(tag)>-1;
            },
            //清除标签左右空格
            cleanTagName(tag){
              return tag.trim();
            },
            //重置输入信息
            resetInput(){
                this.currentTag='';
                this.duplicateFlag=false;
                this.tagSearchResults=[];
                this.searchSelectedIndex=-1;
                this.pauseSearch =false;
            },

        }
    }
</script>

<style lang="scss">
    @import '~@/abstracts/_variables.scss';
    div.tags-input-container {
        position: relative;

        div.tags-input {
            display: block;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            width: 100%;
            height: auto;
            min-height: 100px;
            padding-top: 4px;
            border: 1px solid #cacaca;
            border-radius: 0;
            background-color: #FFFFFF;
            -webkit-box-shadow: inset 0 1px 2px rgba(17, 17, 17, 0.1);
            box-shadow: inset 0 1px 2px rgba(17, 17, 17, 0.1);
            font-family: inherit;
            font-size: 1rem;
            font-weight: normal;
            line-height: 1.5;
            color: #111111;

            div.selected-tag {
                border: 1px solid $dark-color;
                background: $highlight-color;
                font-size: 18px;
                color: $dark-color;
                padding: 3px;
                margin: 5px;
                float: left;
                border-radius: 3px;

                span.remove-tag {
                    margin: 0 0 0 5px;
                    padding: 0;
                    border: none;
                    background: none;
                    cursor: pointer;
                    vertical-align: middle;
                    color: $dark-color;
                }
            }

            input[type="text"].new-tag-input {
                border: 0px;
                margin: 0px;
                float: left;
                width: auto;
                min-width: 100px;
                -webkit-box-shadow: none;
                box-shadow: none;
                margin: 5px;

                &.duplicate-warning {
                    color: red;
                }

                &:focus {
                    box-shadow: none;
                }
            }
        }

        div.tag-autocomplete {
            position: absolute;
            background-color: white;
            width: 100%;
            padding: 5px 0;
            z-index: 99999;
            border: 1px solid rgba(0, 0, 0, 0.2);
            -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
            -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);

            div.tag-search-result {
                padding: 5px 10px;
                cursor: pointer;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                color: $dark-color;
                font-size: 14px;
                background-color: white;

                &:hover {
                    background-color: $highlight-color;
                }
                &.selected-search-index {
                    background-color: $highlight-color;
                }
            }
        }
    }
</style>
